<?php
//测试控制器类
class IndexControl extends Control{

	public function __init(){
        if(is_file(ROOT_PATH . 'Data/lock.php')){
            header('Content-type:text/html;charset=utf-8');
            die('您已经安装过CMS_EDU，如果需要重新安装，请删除Install/Data下面的lock.php文件');
        }

		$setup = include ROOT_PATH . "Data/setup.php";
    	$this->assign('setup',$setup);
	}

    function index(){
    	
    	session('step',1);
    	$this->display();
    }

   public function check(){
   		//处理步骤
   		if(session('step')<1){

   			go('index');
   		}
   		session('step', 2);


   		$gd = gd_info();

   		$system = array(
   			'phpos'			=>	PHP_OS,
   			'phpversion'	=>	PHP_VERSION,
   			'uploadsize'	=>	ini_get('upload_max_filesize'),

   			'gdversion'	=>	$gd['GD Version'],
   			'diskspace'	=>	get_size(disk_free_space('.'))
   			);
 		$this->assign('system',$system);

   		$this->display();
   }


   public function setconfig(){
   	//处理步骤
   		if(session('step')<2){

   			go('check');
   		}
   		session('step', 3);
   		
		$this->display();
   }


    public function install_db(){
    	session('admin',$_POST['admin']);
    	//写数据库配置项
    	$this->_write_config();
    	$this->display();
    }

    /**
     * [_write_config 写数据库配置项]
     * @return [type] [description]
     */
    private function _write_config(){

    	$data = var_export($_POST['db'],TRUE);
   		$str = <<<str
<?php
if (!defined("HDPHP_PATH"))exit('No direct script access allowed');
return $data;
str;
		file_put_contents('../Cms/Common/Config/dbConfig.php', $str);
    }

    /**
     * [createtable 安装库表，插入数据]
     * @return [type] [description]
     */
    public function createtable(){
    	$config = include '../Cms/Common/Config/dbConfig.php';

    	//链接库
    	$link = @mysql_connect($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD']);

      if(!$link) {
        header('Content-type:text/html;charset=utf-8');
        echo '数据库连接错误，请<a href="'.U('setconfig').'" target="_parent">返回上一步</a>'; 
        die;
      }

    	mysql_query('SET NAMES UTF8');
    	//创建库
    	mysql_query('CREATE DATABASE ' . $config['DB_DATABASE'] . ' CHARSET UTF8');
    	//选中库
    	mysql_select_db($config['DB_DATABASE']);
//     	Array
// (
//     [DB_HOST] => 127.0.0.1
//     [DB_USER] => root
//     [DB_PASSWORD] => 
//     [DB_DATABASE] => cms_edu
//     [DB_PORT] => 3306
//     [DB_PREFIX] => hd_
//     [DB_DRIVER] => mysqli
// )
    	//创建表
        $sqlData = file_get_contents('./Data/cms_edu.sql');
        $preg = "/;[\r\n]+/is";
      //拆分为数组
      $arr = preg_split($preg, $sqlData);


      //创建表
      foreach ($arr as $k => $v) {
          if(preg_match("/CREATE\s+TABLE\s+`(.*?)`/is", $v,$t)){
            //替换加表前缀
            $temp = str_replace('`' . $t[1] . '`', '`' . $config['DB_PREFIX'] . $t[1]  . '`', $v);
          
            //创建表
            $bool = mysql_query($temp);
            if($bool){
                echo '<p style="color:green;">创建' . $config['DB_PREFIX'] . $t[1] . '成功</p>';
            }else{
                 echo '<p style="color:red;">创建' . $config['DB_PREFIX'] . $t[1] . '失败<a href="'.U('setconfig').'" target="_parent">返回上一步</a>重新设置</p>';
                die;
            }
          }
      }


      //插入数据
        foreach ($arr as $k => $v) {
          if(preg_match("/INSERT\s+INTO\s+`(.*?)`/is", $v,$t)){
    
            //替换加表前缀
            $temp = str_replace('`' . $t[1] . '`', '`' . $config['DB_PREFIX'] . $t[1]  . '`', $v);
            //插入数据
            $bool = mysql_query($temp);
            if($bool){
                echo '<p style="color:green;">插入' . $config['DB_PREFIX'] . $t[1] . '成功</p>';
            }else{
                 echo '<p style="color:red;">插入' . $config['DB_PREFIX'] . $t[1] . '失败</p>';
            }
        }
      }

      //设置后台用户
      $sql = "INSERT INTO {$config['DB_PREFIX']}user (username,password,is_admin,supper) VALUES ('{$_SESSION['admin']['username']}',md5('{$_SESSION['admin']['password']}'),1,1)";

      mysql_query($sql);
     
      echo "
          <script>
              setTimeout(function(){
                 parent.location.href='./index.php?m=finish'
              },3000);
          </script>
        ";
    	
    }


    public function finish(){
        file_put_contents(ROOT_PATH . 'Data/lock.php', date('Y-m-d H:i:s'));
        $url = array(
            'front_url' =>  dirname(__ROOT__),
            'admin_url' =>  dirname(__ROOT__) . '/admin.php'
            );

        $this->assign('url',$url);

        $this->display();
    }	
}
?>